#include "apue.h"
#include "error.c"

mode_t get_umode(int value){
    mode_t result = 0;

    if(value == 1)
        result = S_IXUSR;
    else if(value == 2)
        result = S_IWUSR;
    else if(value == 3)
        result = S_IWUSR | S_IXUSR;
    else if(value == 4)
        result = S_IRUSR;
    else if(value == 5)
        result = S_IRUSR | S_IXUSR;
    else if(value == 6)
        result = S_IRUSR | S_IWUSR;
    else if(value == 7)
        result = S_IRWXU;

    return result;
}

mode_t get_gmode(int value){
    mode_t result = 0;

    if(value == 1)
        result = S_IXGRP;
    else if(value == 2)
        result = S_IWGRP;
    else if(value == 3)
        result = S_IXGRP | S_IWGRP;
    else if(value == 4)
        result = S_IRGRP;
    else if(value == 5)
        result = S_IXGRP | S_IRGRP;
    else if(value == 6)
        result = S_IRGRP | S_IWGRP;
    else if(value == 7)
        result = S_IRWXG;

    return result;
}

mode_t get_othmode(int value){
    mode_t result = 0;

    if(value == 1)
        result = S_IXOTH;
    else if(value == 2)
        result = S_IWOTH;
    else if(value == 3)
        result = S_IXOTH | S_IWOTH;
    else if(value == 4)
        result = S_IROTH;
    else if(value == 5)
        result = S_IROTH | S_IXOTH;
    else if(value == 6)
        result = S_IROTH | S_IWOTH;
    else if(value == 7)
        result = S_IRWXO;

    return result;
}

int main(int argc, char *argv[])
{
    if(argc < 2 || argc > 3){
        err_quit("exec param error");
    }
    
    int value = atoi(argv[2]);
    mode_t mode;
    mode = get_umode(value / 100) | get_gmode((value % 100) / 10) | get_othmode(value % 10);

    if(chmod(argv[1], mode) < 0){
        err_sys("chmod %s %s error", argv[1], argv[2]);
    }
    return 0;
}
